package org.deri.socializer.activities.chat;

import java.util.Iterator;

import org.deri.socializer.NotificationPanel;

import org.deri.socializer.SocializerApplication;
import org.deri.socializer.activities.start.StartActivity;
import org.deri.socializer.com.xmpp.XmppClient;
import org.deri.socializer.com.xmpp.XmppConversationHistory;
import org.deri.socializer.com.xmpp.XmppGroupChat;
import org.deri.socializer.com.xmpp.XmppMessageHandler;
import org.deri.socializer.com.xmpp.XmppPrivateChat;
import org.deri.socializer.util.XMPPUtilities;
import org.deri.vor.R;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class ChatActivity extends Activity implements XmppMessageHandler {
	
	boolean created = false;
	private NotificationPanel popupPanel;
	SocializerApplication app;
	XmppClient xmppClient;
	
	public void onCreate(Bundle savedInstanceState) {
		System.out.println("[ChatActivity.onCreate] called");
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.chatview);

	    this.app = ((SocializerApplication)getApplicationContext());
        this.xmppClient = this.app.getXMPPClient();
        this.xmppClient.setChatActivity(this);
        this.xmppClient.setXMPPMessageHandler(this);
        this.popupPanel = new NotificationPanel(this.app, this, R.layout.mappopup, R.id.relativeLayoutChat);
        EditorActionHandler editorActionHandler = new EditorActionHandler(this);
        EditText editText = (EditText) findViewById(R.id.chatEditTextInput);
        editText.setOnEditorActionListener(editorActionHandler);

        this.clearMessageField();
        
        if (this.xmppClient.getLastXmppWebChat() instanceof XmppPrivateChat) {
        	this.initializeParticipantsList();
        	this.addConversationHistory();
        } else if (this.xmppClient.getLastXmppWebChat() instanceof XmppGroupChat){
        	System.out.println("[ChatActivity.onCreate] join group chat " + ((XmppGroupChat)this.xmppClient.getLastXmppWebChat()).getRoomName());
        	this.xmppClient.joinGroupChat(((XmppGroupChat)this.xmppClient.getLastXmppWebChat()).getRoomName());
        	this.initializeParticipantsList();
        }
        
        share_button();
        
    	this.created = true;
    }

	public void clearMessageField() {
		TextView view =	(TextView) findViewById(R.id.chatTextView);
		view.setText("");
        view.invalidate();
        ScrollView scroll = (ScrollView)findViewById(R.id.chatScrollView);
        scroll.fullScroll(View.FOCUS_DOWN);
	}
	
	public void addConversationHistory() {
		XmppConversationHistory conversationHistory = this.xmppClient.getLastXmppWebChat().getConversationHistoty();
		TextView view =	(TextView) findViewById(R.id.chatTextView);
		view.append(Html.fromHtml(conversationHistory.toHtmlString()));
        view.invalidate();
        ScrollView scroll = (ScrollView)findViewById(R.id.chatScrollView);
        scroll.fullScroll(View.FOCUS_DOWN);
	}
	
	
    public void addMessage(Participant sender, String message){
    	TextView view =	(TextView) findViewById(R.id.chatTextView);
		view.append(Html.fromHtml("<b><font color='#000000'>" + sender.getUser() + ": </font></b> <font color='#000000'>" + message + "</font><br />"));
        view.invalidate();
        ScrollView scroll = (ScrollView)findViewById(R.id.chatScrollView);
        scroll.fullScroll(View.FOCUS_DOWN);
    }
    
    
    public void addInfo(String info){
    	TextView view =	(TextView) findViewById(R.id.chatTextView);
		view.append(Html.fromHtml("<i><font color='#666666'> " + info + "</font></i><br />"));
        view.invalidate();
        ScrollView scroll = (ScrollView)findViewById(R.id.chatScrollView);
        scroll.fullScroll(View.FOCUS_DOWN);
    }
    
    public void sendMessage() {
    	TextView view =	(TextView) findViewById(R.id.chatEditTextInput);
    	String messageText = view.getText().toString().trim();
    	if (messageText.equalsIgnoreCase(""))
    		return;
    	try {
			this.xmppClient.getLastXmppWebChat().sendMessage("", messageText);
			
			view.setText("");
		} catch (XMPPException e) {
			// TODO: handle exception
			return;
		}
    }
    

	@Override
	public void handleChatMessage(Message message) {
		this.app.lastMessage = message;
		String from = XMPPUtilities.getSenderAddress(message.getFrom());
		if (from.equalsIgnoreCase(this.xmppClient.getLastXmppWebChat().getJid())) {
			final String messageText = message.getBody();
			final ParticipantChat sender = new ParticipantChat(XMPPUtilities.getSenderAddress(message.getFrom()));
			runOnUiThread(new Runnable() {
			    public void run() {
			    	addMessage(sender, messageText);
			    }
			});
		} else {
			// Display Popup
			runOnUiThread(new Runnable() {
			    public void run() {
			    	openPanel();
			    }
			});
		}
	}

	

	
    public void displayChatMessage(Participant participant, String message) {
		System.out.println("handleChatMessage: " + message);
		final Participant sender = participant;
		final String msg = message;
		runOnUiThread(new Runnable() {
		    public void run() {
		    	addMessage(sender, msg);
		    }
		});
	}
	

	@Override
	public void handleGroupChatMessage(Message message) {
		this.app.lastMessage = message;
		if (XMPPUtilities.getRoomJid(message.getFrom()).equalsIgnoreCase(this.xmppClient.getLastXmppWebChat().getJid())) {
			final String messageText = message.getBody();
			final Participant sender = this.xmppClient.getCurrentWebGroupChat().getParticipants().get(message.getFrom());
			if (sender == null)
				return;
			runOnUiThread(new Runnable() {
			    public void run() {
			    	addMessage(sender, messageText);
			    }
			});
		} else {
			runOnUiThread(new Runnable() {
			    public void run() {
			    	openPanel();
			    }
			});
		}

	}
	
	@Override
	public void handleWebGroupChatPresence(Presence presence) {
		String user = XMPPUtilities.getUser(presence.getFrom());
		String info = "";
		
		if (presence.getType() == null) { return; }
		
		if (XMPPUtilities.hasJoined(presence))
			info = user + " has joined the chat";
		else
			info = user + " has left the chat";
		final String infoFinal = info;
		Iterator<Participant> participants = this.xmppClient.getCurrentWebGroupChat().getParticipants().values().iterator();
		String participantsList = "";
		while (participants.hasNext())
			participantsList += participants.next().getUser() + " ";
		final String list = participantsList;
		runOnUiThread(new Runnable() {
		    public void run() {
		    	updateParticipantsList(list);
		    	addInfo(infoFinal);
		    }
		});
	}

	private void initializeParticipantsList() {
		Iterator<Participant> participants = this.xmppClient.getLastXmppWebChat().getParticipants().values().iterator();
		String participantsList = "";
		while (participants.hasNext())
			participantsList += participants.next().getUser() + " ";
		final String list = participantsList;
		runOnUiThread(new Runnable() {
		    public void run() {
		    	updateParticipantsList(list);
		    }
		});
	}
	
	private void updateParticipantsList(String list) {
		TextView view = (TextView) findViewById(R.id.chatParticipants);
		view.setText(Html.fromHtml("<font color='#eeeeee'><b>Participants:</b> " + list.trim() + " </font>"));
		view.invalidate();
	}
	
	public void handleGroupChatInvitation(String from, String subject, String message) {
		
	}
	

	private void openPanel() {
	    this.popupPanel.hide();
        if (this.app.lastMessage.getType() == Message.Type.chat) {
        	this.popupPanel.showNewPrivateChatMessageNotification(this, this.xmppClient, true);
        } else {
        	this.popupPanel.showNewGroupChatMessageNotification(this, this.xmppClient, true);
        }
	}
	
	
	class EditorActionHandler implements OnEditorActionListener{

		ChatActivity chatActivity = null;
		
		
		public EditorActionHandler(ChatActivity chatActivity) {
			this.chatActivity = chatActivity;
		}
		
		@Override  
	    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {  
	        Log.v("LOG", "onEditorAction");
	    	if(event!=null && event.getAction()==KeyEvent.ACTION_DOWN){  
	            //Handle enter key  
	    		this.chatActivity.sendMessage();
	            return true;  
	        }  
	        if(actionId == EditorInfo.IME_ACTION_NEXT){  
	            //Handle IME NEXT key  
	        	this.chatActivity.sendMessage();
	            return true;  
	        }  
	        if(actionId == EditorInfo.IME_ACTION_DONE){  
	            //Handle IME DONE key  
	        	this.chatActivity.sendMessage();
	            return true;  
	        }  
	        return false;  
	    }  

	}

	@Override
	protected void onDestroy() {
	    super.onDestroy();
	    this.app.checkActivityState();
	}

	@Override
	protected void onPause() {
	    super.onPause();
	    created = false;
	    SocializerApplication.runningActivities--;
	}
	
	@Override
	protected void onResume() {
	    if (!created) {
	    	Intent intent = getIntent();
	    	finish();
	    	startActivity(intent);
	    }
		super.onResume();
		SocializerApplication.runningActivities++;
	}
	
	
	private void share_button(){
		Button button = (Button) findViewById(R.id.btnBack);
		button.setOnClickListener(ms_layout);

		// About Button OnClick
		button = (Button) findViewById(R.id.btnAbout);
		button.setOnClickListener(ms_layout);

		// Home Button OnClick
		button = (Button) findViewById(R.id.btnHome);
		button.setOnClickListener(ms_layout);
		
//		ImageView im  = (ImageView) findViewById(R.id.vor_icon);
//		im.setClickable(true);
//		im.setOnClickListener(ms_layout);
//
//		im = (ImageView) findViewById(R.id.nuig_icon);
//		im.setClickable(true);
//		im.setOnClickListener(ms_layout);
//
//		im = (ImageView) findViewById(R.id.deri_icon);
//		im.setClickable(true);
//		im.setOnClickListener(ms_layout);
	}
    
    
    private OnClickListener ms_layout	=	new OnClickListener(){

		@Override
		public void onClick(View v) {
			switch (v.getId()){
			case R.id.btnAbout  : { jump(72); break;}
			case R.id.btnHome 	: { jump(2); break;}
			case R.id.btnBack  	: { back(); break;}
//			case R.id.vor_icon  : { jump(3); break;}
//			case R.id.deri_icon : { jump(19); break;}
//			case R.id.nuig_icon : { jump(40); break;}
			}
		}
    };
    
    
    private void jump(int page){
    	Intent i = new Intent();
    	i.putExtra("cl",page);
    	i.setClassName("org.deri.vor", "org.deri.vor.VovolOceanRaceActivity");
		startActivity(i);
		finish();
    }
   
    public void back() {
    	Intent intent = new Intent(getApplicationContext(), StartActivity.class);
    	startActivity(intent);
    	finish();
    
    }
}




